package com.jekun.helloworld.designmode.proxy.aoptest;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * 切面类
 *
 * @author Administrator
 */
@Aspect
@Slf4j
@Component("smsAndMailSenderMonitor")
public class SMSAndMailSenderMonitor {

    @Pointcut("@annotation(com.jekun.helloworld.designmode.proxy.aoptest.SMSAndMailSender)")
    public void pointcut() {

    }

    @Before("pointcut().*(..)")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        boolean active = method.getAnnotation(SMSAndMailSender.class).isActive();
        if (!active) {
            return;
        }
        System.out.println("方法执前执行");
    }

    /**
     * 在所有标记了@SMSAndMailSender的方法中切入
     *
     * @param joinPoint
     * @param result
     */
    @AfterReturning(value = "pointcut()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        boolean active = method.getAnnotation(SMSAndMailSender.class).isActive();
        if (!active) {
            return;
        }
        String smsContent = method.getAnnotation(SMSAndMailSender.class).smsContent();
        String mailContent = method.getAnnotation(SMSAndMailSender.class).mailContent();
        String subject = method.getAnnotation(SMSAndMailSender.class).subject();
        System.out.println("方法执行后执行");

    }

    /**
     * 在抛出异常时使用
     *
     * @param joinPoint
     * @param ex
     */
    @AfterThrowing(value = "@annotation(SMSAndMailSender)", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Throwable ex) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String subject = method.getAnnotation(SMSAndMailSender.class).subject();
        System.out.println("抛出异常后执行");

    }
}